var shopcartEvent = function() {};
$(function() {
	var html = [];
	shopcartEvent.prototype = {
		//编辑购物车
		editCart: function() {
			var thisEvent = this;
			//编辑所有
			$("#editCart").unbind().on("click", function(e) {
        console.log('edit');
				if( 0 == $("div[id^=shop_]").length){
					return;
				}
				var titleSpan = $(this).find("span:first");
				var isEdit = ("编辑" == titleSpan.html()) ? true : false;
				thisEvent.showDeleteText(isEdit);
			});
		},
		//显示编辑完成
		showDeleteText:function(isEdit){
			var titleSpan = $('#editCart').find("span:first");
			if (isEdit) {
				$("div.delete").show().animate({
					"width": "18%"
				}, 400);
				$("div[name='productName']").hide(400);
				$("div[name='addReduce']").show(400);
				titleSpan.html("完成");
			} else {
				$("div.delete").animate({
					"width": "0%"
				}, 400).hide(100);
				$("div[name='productName']").show(400);
				$("div[name='addReduce']").hide(400);
				titleSpan.html("编辑");
			}
		},
		//添加减少数量
		addOrSubNumber: function(cartData, user) {
			var strId = '',
				suffix = '',
				quantity = 0,
				type = '',
				coin = 0,
				price = 0,
				sku = "",
				subCoinTotal = 0,
				subTotal = 0,
				thisEvent = this;
			//增加，减少商品数量
			$("#main").on("click", "a[id^='reduce_'],a[id^=add_]", function() {
				//
				strId = $(this).prop("id");
				suffix = strId.match(/_\w*/);
				_suffix = strId.match(/_\w/);
				type = $(this).html();
				if (suffix) {
					quantity = parseInt($("#quantity" + suffix).val());
					coin = parseInt($("#coin" + suffix).html());
					price = parseFloat($("#price" + suffix).html().match(/(-?\d*)\.?\d+/)[0]);
					tips = $(this).attr("tip");
					subCoinTotal = parseInt($("#subCoinTotal" + _suffix).html());
					subTotal = parseFloat($("#subTotal" + _suffix).html().match(/(-?\d*)\.?\d+/)[0]);
					if ("+" == type) {
						quantity++;
						subCoinTotal += coin
						subTotal += price
					} else {
						if (quantity < 2) {
							return;
						}
						quantity--;
						subCoinTotal -= coin
						subTotal -= price
					}
					//调用接口修改商品或套件数量
					thisEvent.modifyProductNum(type, tips, user);
					$("#quantity" + suffix).val(quantity);
					$("#qty" + suffix).html("x" + quantity);

					$("#subCoinTotal" + _suffix).html(subCoinTotal);
					$("#subTotal" + _suffix).html("&yen;" + subTotal.toFixed(2));
				}
			});
		},
		//删除商品
		deletProduct: function(user) {
			var thisModel = this;
			$("#main").on("click", "div[name='deleteCurentCart']", function() {
				var title = $(this).html();
				var that = $(this);
				var tips = JSON.parse( $(this).attr("tip") );
				var id = $(this).attr("id");
				var goodsSuffix = id.match(/_\w*/)[0];
				var shopSuffix = id.match(/_\w/)[0];
				var goodsCount = $("ul[id^=goods"+ shopSuffix +"]").length;
				$.ajax({
					type: "DELETE",
					url: CONFIG_MANAGER.RequstUrl + "v1/cart/removebyid/" + CONFIG_MANAGER.orgId + "/" + user.id + "/" + tips.cart_id,
					async: true,
					beforeSend:function(){ $.closeWaiting(); }
				}).done(function(data) { 
					$.toast("删除成功");
					thisModel.calculatePrice(data);
					if( 1 == goodsCount ){
						setTimeout(function(){ $("div[id^=shop"+ shopSuffix +"]").remove(); }, 500);
					}else if( 1 < goodsCount ){
						setTimeout(function(){ $("ul[id^=goods"+ goodsSuffix +"]").remove(); }, 500);
						var subTotal = parseFloat( $("#subTotal"+shopSuffix).html().match(/(-?\d*)\.?\d+/)[0] );
						var subCoinTotal = parseFloat( $("#subCoinTotal"+shopSuffix).html().match(/(-?\d*)\.?\d+/)[0] );
						//减去当前商品星币数和价钱
						subTotal -= parseInt(tips.qty) * parseFloat( tips.price );
						subTotal = (subTotal<0)?0:subTotal;
						subCoinTotal -= parseInt(tips.coin) * parseFloat( tips.price );
						subCoinTotal = (subCoinTotal<0)?0:subCoinTotal;
						$("#subTotal"+shopSuffix).html(subTotal.toFixed(2));
						$("#subCoinTotal"+shopSuffix).html(subCoinTotal.toFixed(2));
					}
				}).fail(function(data) {
					$.toast(data.responseJSON.Message);
				}).always(function(data){
					$.closeWaiting();
				});
				
			});
		},
		//调用接口修改商品个数
		modifyProductNum: function(type, tips, user) {
			var thisEvent = this;
			var requestUrl = CONFIG_MANAGER.RequstUrl;
			if ('+' == type) {
				//requestUrl += "v1/cart/plus/" + CONFIG_MANAGER.orgId + "/" + user.id + "/" + cartid;
				requestUrl += "v1/cart/plusbyid/" + CONFIG_MANAGER.orgId + "/" + user.id + "/" + tips;
			} else {
				//requestUrl += "v1/cart/minus/" + CONFIG_MANAGER.orgId + "/" + user.id + "/" + cartid;
				requestUrl += "v1/cart/minusbyid/" + CONFIG_MANAGER.orgId + "/" + user.id + "/" + tips;
			}
			$.ajax({
				type: "PUT",
				url: requestUrl,
				async: true,
				headers: {
					token: user.token
				}
			}).done(function(data) {
				//计算总价
				thisEvent.calculatePrice(data);
			}).fail(function(data) {
				var infor = JSON.parse(data);
				$.toast(infor.Message);
			});
		},
		//所有checkbox事件
		checkCartProduct: function(user, cartData) {
			var thisEvent = this;
			$("body").on("click", "input[id^='checkbox-1-1']", function() {
				var idString = $(this).attr("id");
				var isChecked = false;
				var checkedIDs = [];
				//店铺名称前的checkbox
				if (/^checkbox-1-1_shop/.test(idString)) {
					var length = idString.length;
					var shopIndex = idString.substr((length - 1), 1);
					isChecked = $(this).is(":checked");
					$.each($("input[id^='checkbox-1-1_goods_" + shopIndex + "']"), function(i, goods) {
						var tips = JSON.parse($(goods).attr("tip"));
						checkedIDs.push( ('suite'==tips.type) ?  tips.suite_no : tips.sku_id );
					});
					if (0==checkedIDs.length) {
						return;
					}
					$("input[id^='checkbox-1-1_goods_" + shopIndex + "']").prop("checked", isChecked);
					thisEvent.updateCheckedStatus(checkedIDs, isChecked, user);
					if (0 == $("input[id^='checkbox-1-1_shop']:not(:checked)").length) {
						isChecked = true;
					} else {
						isChecked = false;
					}

					$("#checkbox-1-1_selectAll").prop("checked", isChecked);
					console.log(JSON.stringify(checkedIDs));
				}
				//商品名称前的checkbox
				else if (/^checkbox-1-1_goods/.test(idString)) {
					var shopId = $(this).attr("id").substr(-3, 1);
					isChecked = $(this).is(":checked");
					var tips = JSON.parse($(this).attr("tip"));
					checkedIDs.push( ('suite'==tips.type) ?  tips.suite_no : tips.sku_id );
					thisEvent.updateCheckedStatus(checkedIDs, isChecked, user);
					if (0 == $("input[id^='checkbox-1-1_goods_" + shopId + "']:not(:checked)").length) {
						isChecked = true;
					} else {
						isChecked = false;
					}
					$("input[id='checkbox-1-1_shop_" + shopId + "']").prop("checked", isChecked);
					if (0 == $("input[id^='checkbox-1-1_goods']:not(:checked)").length) {
						isChecked = true;
					} else {
						isChecked = false;
					}
					$("#checkbox-1-1_selectAll").prop("checked", isChecked);
					console.log("checkbox-1-1_goods");
				}
				//选择所有的checkbox
				else if (/^checkbox-1-1_selectAll/.test(idString)) {
					isChecked = $(this).is(":checked");
					$.each($("input[id^='checkbox-1-1_goods_']"), function(i, goods) {
						var tips = JSON.parse($(goods).attr("tip"));
						checkedIDs.push( ('suite'==tips.type) ?  tips.suite_no : tips.sku_id );
					});
					thisEvent.updateCheckedStatus(checkedIDs, isChecked, user);
					$("input[id^='checkbox-1-1_goods']").prop("checked", isChecked);
					$("input[id^='checkbox-1-1_shop']").prop("checked", isChecked);
				}
			});
		},
		//请求选中，取消选中接口
		updateCheckedStatus: function(idArray, checked, user) {
			var thisEvent = this;
			var requestUrl = CONFIG_MANAGER.RequstUrl + "v1/cart/checked/" + CONFIG_MANAGER.orgId + "/" + user.id + "/";
			if (checked) {
				requestUrl += "1";
			} else {
				requestUrl += "0";
			}
			$.ajax({
				type: "POST",
				url: requestUrl,
				async: true,
				contentType: 'application/json',
				data: JSON.stringify(idArray),
				beforeSend:function(){ }
			}).done(function(data) {
				console.log("update checked " + checked + " successed");
				thisEvent.calculatePrice(data);
			}).fail(function(data) {
				var infor = JSON.parse(data);
				$.toast(infor.Message);
			}).always(function(){
				
			});
		},
		//计算总价,重新计算购物车中商品个数
		calculatePrice: function(data) {
			var cacheproductcount = 0;
			var user = getLocalStorage(STORAGE_MANAGER.user);
			var strId = "",
				qty = 0,
				coin = 0,
				goodsCount = 0,
				isChecked = false;
			if (data) {
				$.each(data.supplier, function(i, supplier) {
					//平台
					if (1 == supplier.type) {
						$.each(supplier.suites, function(i, suite) {
							isChecked = (suite.is_checked == 1);
							qty = isChecked ? suite.qty : 0;
							goodsCount += qty * suite.goods.length;
						});
					} else if (2 == supplier.type) {
						$.each(supplier.goods, function(i, goods) {
							isChecked = (goods.is_checked == 1);
							qty = isChecked ? goods.qty : 0;
							goodsCount += qty;
						});
					}					
				});
				$("#total").html(data.total_money);
				$("#totalCoin").html(data.total_coin);				
			}else{
				$("#total").html(0);
				$("#totalCoin").html(0);				
			}
			//选中的商品个数
			$("#goodsCount").html(goodsCount);			
			
      //选中购物车中的商品之后重新计算商品总个数
      $.ajax({
      	type: "GET",
      	headers:{ token: user.token },
      	url: CONFIG_MANAGER.RequstUrl + "v1/cart/sum/" + user.id,
      	async:true,
      }).done(function(data){
      	$.closeWaiting();
      	setLocalStorage(STORAGE_MANAGER.cacheproductcount, data.count);
      	if(AGENT_CLIENT.APP){
      		if(0==data.count){
      			$("#editCart>span:first").html('编辑');
      		}
      		plus.webview.getWebviewById("../home/main.html").evalJS("getShopcartProductCount()");
      		plus.webview.currentWebview().opener().evalJS('getShopcartProductCount()');
      	}else{
      		if(data.count > 0){
      			$("#totalProductCount").html(data.count);
      		}else{
      			$("#totalProductCount").hide();
      		}
      	}
      });
		},
		//满减活动
		shopSubtract: function(goodsData, user) {
		//满减活动弹出框
		$("#main").on("click", "span[id^=full_subtract_]", function() {
			var supplierID = parseInt($(this).attr("id").match(/\d+/)[0]);
			var subtracts = goodsData.supplier[supplierID].full_subtract;
			html = [];
			$.each(subtracts, function(i, subtract) {
				html.push('<div name="item_coupon" class="shp-gwcny_center">');
				html.push('<p class="shp-ms shp-ms1">满减</p>');
				html.push('<p class="shp-coudan">');
				html.push(subtract.name);
				html.push('</p>');
				html.push('<p name="get_coupon" tip=' + JSON.stringify(subtract) + ' class="ob-cha-select"><a style="width:58px;"  class="receive_button">选择</a></p>')
				html.push('</div>');
			});
			$("#active_item").html(html.join(''));
			$("#active_title").html("满减");
			$("#givegoodsback").show();
			$("#givegoodspop").show();
			setTimeout(function() {
				$("#givegoodspop").addClass("moveFromBottom-moved");
			}, 200);
		});
		//选中店铺某个满减
		$("#givegoodspop").on("click", "#active_item>div[name='full_subtract_']", function() {
			var supplierID = parseInt($(this).attr("id").match(/\d+/)[0]);
			var subtract = goodsData.supplier[supplierID].full_subtract;
			html = [];
			html.push('<div class="shp-cart-item-core sub-shp-gwcny">');
			html.push('<p class="shp-ms">换购</p>');
			html.push('<div name="remove_give" class="cart-product-cell-3">');
			html.push('<i class="iconfont icon-diancha"></i>');
			html.push('</div>');
			html.push('<a class="sub-cart-product-cell-1" href="javascript:void(0);">');
			html.push('<img class="sub-cart-photo-thumb" src="' + getImageUrl(item.logo, 59, 59) + '">');
			html.push('</a>');
			html.push('<div class="cart-product-cell-2">');
			html.push('<div class=" cart-product-name1"><span>' + item.name + '</span></div>');
			html.push('<div class="shp-cart-opt">');
			html.push('<p class="sub-wastebin">x' + item.qty + '</p>');
			html.push('</div>');
			html.push('</div>');
			html.push('</div>');
			$("li#goods_0_0>div.items").append(html.join(''));
			$("#givegoodspop").removeClass("moveFromBottom-moved");
			setTimeout(function() {
				$("#givegoodspop").hide();
				$("#givegoodsback").hide();
			}, 200);
		});
		},
		//套件事件
		shopSuites: function(goodsData, user) {
			var thisEvent = this;
			//套件活动弹出框
			$("#main").on("click", "span[id^=suites_]", function() {
				var shopID = parseInt($(this).attr("id").match(/\d+/)[0]);
				var suites = goodsData.supplier[shopID].suites;
				html = [];
				$.each(suites, function(i, suite) {
					html.push('<div class="shop-title mbbottom"><div class="item"><div class="shop-title-content">');
					html.push('<span class="shop-title-name">');
					html.push('<b class="checkboxFour">');
					html.push('<input type="checkbox" value="' + suite.suite_no + '" id="checkbox-1-1_suit_' + shopID + '" name="RadioGroup1" class="checkbox-gx">');
					html.push('<label for="checkbox-1-1_suit_' + shopID + '"></label>');
					html.push('</b>');
					html.push(suite.suite_name);
					html.push('</span>');
					html.push('</div></div></div>');
					$.each(suite.goods, function(j, goods) {
						html.push('<div class="shp-cart-item-core shp_gwcny_suit">');
						html.push('<a class="cart-product-cell-1" href="javascript:;">');
						html.push('<img class="cart-photo-thumb" src="' + getImageUrl(goods.logo, 62, 59) + '">');
						html.push('</a>');
						html.push('<div  style="width:75%;" class="cart-product-cell-2">');
						html.push('<div class="cart-product-name1"><a href="#"><span>' + goods.name + '</span></a></div>');
						html.push('<div class="cart-product-name w40"><a href="#"><span>' + goods.spec + '</span></a></div>');
						html.push('<div class="shp-cart-opt">');
						html.push('<p class="cart-price"><span>x' + goods.qty + '</span>￥' + goods.shop_price + '</p>');
						html.push('</div></div></div>');
					});
				});
				$("#active_item").html(html.join(''));
				$("#active_title").html("套件");
				$("#givegoodsback").show();
				$("#givegoodspop").show();
				setTimeout(function() {
					$("#givegoodspop").addClass("moveFromBottom-moved");
				}, 200);
			});
			//点击弹出框中的套件checkbox
			$("body").on("click", "input[id^=checkbox-1-1_suit_]", function() {
				var suite_no = $(this).val();
				var requestData = {
					suite_no: suite_no,
					member_id: user.id,
					session_id: getSessionID(),
					qty: 0,
					org_id: CONFIG_MANAGER.orgId
				};
				$.ajax({
					type: "POST",
					url: CONFIG_MANAGER.RequstUrl + "v1/cart/add/suite",
					async: true,
					contentType: 'application/json',
					headers: {
						token: user.token
					},
					data: JSON.stringify(requestData),
				}).done(function(data) {}).always(function(data) {}).fail(function(data) {
					$.toast("请求失败");
				});
			});
		},
		//点击去结算
		goBalance: function(goodsData, user) {
			//点击去结算
			$("#goBanlance").on("click", function() {
				if (parseInt($("#goodsCount").html()) < 1) {
					$.toast("请选择一件商品");
				} else {
					var confirmData = {
						org_id: CONFIG_MANAGER.orgId,
						member_id: user.id,
						address_id: 0,
						referrer: user.referer,
						delivery: 1,
						delivery_point: 3101,
						instant_buy: 0,
						share_ids: [],
						coupono:'',
						target_id: [],
						supplier: '',
					};
					var supplier = goodsData.supplier
					var i = 0;
					var j = 0;
					var checkGoods = $("input[id^=checkbox-1-1_goods_]");
					while (checkGoods[i]){
						var tips = JSON.parse( $(checkGoods[i]).attr('tip') );
						if( $(checkGoods[i]).is(":checked") ){
							if('suite' == tips.type){
								confirmData.target_id.push({suite_no:tips.suite_no, qty:tips.qty});
							}else{
								confirmData.target_id.push({sku_id:tips.sku_id, qty:tips.qty});
							}
							//TODO 添加share_id
						}
						i++;
					}
					setLocalStorage(STORAGE_MANAGER.confirmOrderData, confirmData);
					redirect("confirmOrder.html");
				}
			});
		}
	}
});